<?php

/**
 * 添加项目类
 * @author  ZhouHaoHua <53027327@qq.com>
 * @package
 */
class Project {
    /**
     * 项目路径
     * @var
     */
    private $dir;
    /**
     * MVC及配置文件的源模板目录
     * @var
     */
    private $fileSource;
    /**
     * 系统用户名
     * @var
     */
    private $user;

    /**
     * @param $dir 项目的根路径
     */
    public function __construct($dir) {
        $this->dir        = $dir;
        $this->fileSource = Z_DIR . '/artisan/resources';
        $this->user       = get_current_user();
    }

    /**
     * 添加项目（自动添加全部）
     * @return $this
     */
    public function add() {
        if (!$this->isExists()) {
            $this->addProjectDir()
                ->addConfig()
                ->addEntryFile()
                ->addControllers('index')
                ->addModels()
                ->addMainPageViews('html5')
                ->addMainPageViews('top')
                ->addMainPageViews('bottom')
                ->addViews('index')
                ->addHtaccess()
                ->addLogDir()
            ;
            return true;
        }
        echo 'Error: Project has exists:'.$this->dir."\n";
        return false;
    }

    /**
     * 添加入口文件
     * @return $this
     */
    public function addEntryFile() {
        $pr = array('{AUTHOR}' => get_current_user(), '{DATE}' => date('Y-m-d'));

        $index = $this->dir . '/index.php';
        if (!file_exists($index)) {
            $content = file_get_contents($this->fileSource . '/index.php');
            $content = strtr($content, $pr);
            file_put_contents($index, $content);
        } else {
            echo 'Error: create file Fail. File exists.' . $index . "\n";
        }
        return $this;
    }

    /**
     * 删除项目
     * @return $this
     */
    public function del() {
        $dir = realpath($this->dir);
        if (\Z::DirFile()->delDir($dir)) {
            echo 'del Dir OK. ' . $dir . "\n";
        } else {
            echo 'del Dir Fail. ' . $dir . "\n";
        }
        return $this;
    }

    /**
     * 添加项目文件夹
     * @return $this
     */
    public function addProjectDir() {

        if (\Z::DirFile()->createDir($this->dir, 0755)) {
            echo 'createDir OK. ' . realpath($this->dir) . "\n";
        } else {
            echo 'createDir Fail. ' . "\n";
        }
        return $this;
    }

    /**
     * 添加配置文件
     * @return $this
     */
    public function addConfig() {
        $pr = array('{AUTHOR}' => get_current_user(), '{DATE}' => date('Y-m-d'));

        $dir = $this->dir . '/config';
        if (\Z::DirFile()->createDir($dir, 0755)) {
            echo 'createDir OK. ' . realpath($dir) . "\n";
            if(copy($this->fileSource . '/htaccess.deny.r', $dir . '/.htaccess')){
                echo 'createFile OK. ' . realpath($dir . '/.htaccess') . "\n";
            }
            $c = $dir . '/config.php';
            if (!file_exists($c)) {
                $content = file_get_contents($this->fileSource . '/config_config.r');
                $content = strtr($content, $pr);
                file_put_contents($c, $content);
            } else {
                echo 'Error: create file Fail. File exists.' . $c . "\n";
            }
            $d = $dir . '/db.php';
            if (!file_exists($d)) {
                $content = file_get_contents($this->fileSource . '/config_db.r');
                $content = strtr($content, $pr);
                file_put_contents($d, $content);
            } else {
                echo 'Error: create file Fail. File exists.' . $d . "\n";
            }
            $w = $dir . '/web.php';
            if (!file_exists($w)) {
                $content = file_get_contents($this->fileSource . '/config_web.r');
                $content = strtr($content, $pr);
                file_put_contents($w, $content);
            } else {
                echo 'Error: create file Fail. File exists.' . $w . "\n";
            }
            $c = $dir . '/cache.php';
            if (!file_exists($c)) {
                $content = file_get_contents($this->fileSource . '/config_cache.r');
                $content = strtr($content, $pr);
                file_put_contents($c, $content);
            } else {
                echo 'Error: create file Fail. File exists.' . $c . "\n";
            }
        } else {
            echo 'Error: createDir Fail. ' . "\n";
        }
        return $this;
    }

    /**
     * 添加.htaccess文件
     * @return $this
     * @author ZhouHaoHua <53027327@qq.com>
     */
    public function addHtaccess() {
        if(copy($this->fileSource . '/htaccess.r', $this->dir . '/.htaccess')){
            echo 'createFile OK. ' . realpath($this->dir . '/.htaccess') . "\n";
        }
        return $this;
    }

    /**
     * 添加控制器文件夹
     * 同时创建默认的index控制器
     * @param string $conName 控制器名称
     * @return $this
     */
    public function addControllers($conName = 'index') {
        $dir = $this->dir . '/controllers';
        if (\Z::DirFile()->createDir($dir, 0755)) {
            echo 'createDir OK. ' . realpath($dir) . "\n";
            if(copy($this->fileSource . '/htaccess.deny.r', $dir . '/.htaccess')){
                echo 'createFile OK. ' . realpath($dir . '/.htaccess') . "\n";
            }
            $file = $dir . '/index.php';
            if ($conName) {
                $st   = str_replace(array('_', ' ', '-'), array('/', '/', '/'), $conName);
                $file = $dir . '/' . $st . '.php';
                \Z::DirFile()->createDir(dirname($file), 0755);
                if (!file_exists($file)) {
                    $pr      = array('{AUTHOR}' => get_current_user(), '{CONTROLLERS}' => $conName, '{DATE}' => date('Y-m-d'), '{TPL}' => str_replace('_', '/', $conName));
                    $content = file_get_contents($this->fileSource . '/controllers_index.r');
                    $content = strtr($content, $pr);
                    file_put_contents($file, $content);
                    echo 'createFile OK. ' . realpath($file) . "\n";
                } else {
                    echo 'Error: create file Fail. File exists.' . $file . "\n";
                }
            } else {
                echo 'Error: no conName.' . "\n";
            }
        } else {
            echo 'Error: createDir Fail. ' . "\n";
        }
        return $this;
    }

    /**
     * 添加模块文件夹
     * 主要是添加数据表方面的模块
     * @param string $table 数据表名称。此值若为空就复制默认的文件
     * @return $this
     */
    public function addModels($table = '') {
        $dir = $this->dir . '/models';
        $r   = false;
        if (\Z::DirFile()->createDir($dir, 0755)) {
            echo 'createDir OK. ' . realpath($dir) . "\n";
            $r = true;
            if(copy($this->fileSource . '/htaccess.deny.r', $dir . '/.htaccess')){
                echo 'createFile OK. ' . realpath($dir . '/.htaccess') . "\n";
            }
        } else {
            $r = false;
            echo 'Error: createDir Fail. ' . "\n";
        }
        if ($r == true) {
            if ($table) {   //创建数据表对应类
                $st       = str_replace(array('_', ' ', '-'), array('/', '/', '/'), $table);
                $fullFile = $dir . '/' . $st . '.php';
                \Z::DirFile()->createDir(dirname($fullFile), 0755);
                if (!file_exists($fullFile)) {
                    $className = $table;
                    $pr        = array('{AUTHOR}' => get_current_user(), '{TABLE}' => $className, '{DATE}' => date('Y-m-d'));
                    $content   = file_get_contents($this->fileSource . '/models_DB.r');
                    $content   = strtr($content, $pr);
                    file_put_contents($fullFile, $content);
                } else {
                    echo 'Error: file exists. ' . $fullFile . "\n";
                }
            } else {
                $a = $dir . '/Application.php';
                if (!file_exists($a)) {
                    copy($this->fileSource . '/models_Application.r', $a);
                } else {
                    echo 'Error: create file Fail. File exists.' . $a . "\n";
                }
                $u = $dir . '/Url.php';
                if (!file_exists($u)) {
                    copy($this->fileSource . '/models_Url.r', $u);
                } else {
                    echo 'Error: create file Fail. File exists.' . $u . "\n";
                }
                $h = $dir . '/Html.php';
                if (!file_exists($h)) {
                    copy($this->fileSource . '/models_Html.r', $h);
                } else {
                    echo 'Error: create file Fail. File exists.' . $h . "\n";
                }
                $aa = $dir . '/Abstract/Action.php';
                if (!file_exists($aa)) {
                    \Z::DirFile()->createDir($dir . '/Abstract', 0755);
                    copy($this->fileSource . '/models_Abstract_Action.r', $aa);
                } else {
                    echo 'Error: create file Fail. File exists.' . $aa . "\n";
                }
            }
        }
        return $this;
    }

    /**
     * 添加html大模板结构文件
     * @param string $name    html标准名，如：html5
     * @param string $version 模板的版本，默认是pc
     * @return $this
     */
    public function addMainPageViews($name = 'html5', $version = 'pc') {
        $dir = $this->dir . '/views/' . $version . '/MainPage/' . $name;
        if (\Z::DirFile()->createDir($dir, 0755)) {
            $ch = $dir . '/' . $name . '.tpl.php';
            if (!file_exists($ch)) {
                \Z::DirFile()->copy($this->fileSource . '/MainPage/' . $name, $dir);
            } else {
                echo 'Error: create file Fail. File exists.' . $ch . "\n";
            }
        }
        return $this;
    }

    /**
     * 添加视图文件夹
     * @param string $name    视图名称。如：index、orders/ordersSet等
     * @param string $version 模板的版本，默认是pc
     * @return $this
     */
    public function addViews($name = 'index', $version = 'pc') {
        $dir         = $this->dir . '/views/' . $version;
        $controllers = $name;
        $controllers = str_replace(array('_', ' ', '-'), array('/', '/'), $controllers);
        $finalName   = preg_split('/\/|\_/', $controllers);
        $finalName   = $finalName[count($finalName) - 1];
        if (\Z::DirFile()->createDir($dir, 0755)) {
            $dir = realpath($dir);
            echo 'createDir OK. ' . realpath($dir) . "\n";
            if(copy($this->fileSource . '/htaccess.deny.r', $dir . '/.htaccess')){
                echo 'createFile OK. ' . realpath($dir . '/.htaccess') . "\n";
            }
            $cDir = $dir . '/' . $controllers;
            \Z::DirFile()->createDir($cDir, 0755);
            if ($name == 'index') {
                if (!file_exists($cDir.'/index.tpl.php') || !file_exists($cDir.'/index.html')) {
                    \Z::DirFile()->copy($this->fileSource . '/' . $name, $cDir);
                } else {
                    echo 'Error: create file Fail. File exists.' . $cDir . "\n";
                }
            } else {
                $file = '/' . $controllers . '/' . $finalName;

                $t = $dir . $file . '.tpl.php';
                if (!file_exists($t)) {
                    file_put_contents($t, '<p>这是' . $name . '测试</p>', FILE_APPEND);
                } else {
                    echo 'Error: create file Fail. File exists.' . $t . "\n";
                }

                $j = $dir . $file . '.js';
                if (!file_exists($j)) {
                    file_put_contents($j, 'alert("This ' . $name . '");', FILE_APPEND);
                } else {
                    echo 'Error: create file Fail. File exists.' . $j . "\n";
                }

                $c = $dir . $file . '.css';
                if (!file_exists($c)) {
                    file_put_contents($c, 'h1{ font-size:24px;}', FILE_APPEND);
                } else {
                    echo 'Error: create file Fail. File exists.' . $c . "\n";
                }
                $conf = $dir . $file . '.conf';
                if (!file_exists($conf)) {
                    file_put_contents($conf, '', FILE_APPEND);
                } else {
                    echo 'Error: create file Fail. File exists.' . $conf . "\n";
                }
            }
            $iDir = $cDir . '/image';
            \Z::DirFile()->createDir($iDir, 0755);
        } else {
            echo 'createDir Fail. ' . "\n";
        }
        return $this;
    }

    /**
     * 判断当前项目是否已经存在
     * @return bool 若已存在返回true，不存在则返回false
     */
    public function isExists() {
        if (!file_exists($this->dir)) {
            return false;
        }
        return true;
    }

    /**
     * 添加记录错误日志的文件夹
     * @return $this
     * @author ZhouHaoHua <53027327@qq.com>
     */
    public function addLogDir(){
        $log_dir = $this->dir.'/log/';
        if (\Z::DirFile()->createDir($log_dir, 0755)) {
            echo 'createLogDir OK. ' . realpath($log_dir) . "\n";
            if(copy($this->fileSource . '/htaccess.deny.r', $log_dir . '/.htaccess')){
                echo 'createFile OK. ' . realpath($log_dir . '/.htaccess') . "\n";
            }
        } else {
            echo 'createLogDir Fail. ' . "\n";
        }
        return $this;
    }
}